package com.fyyg.common.randomnumber;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class RandomNumberTwoUtil {
	
	 /** 
     * 概率选择 
     * @param keyChanceMap key为唯一标识，value为该标识的概率，是去掉%的数字 
     * @return 被选中的key。未选中返回null 
     */  
     public static String chanceSelect(Map<String, Integer> keyChanceMap) {  
          if(keyChanceMap == null || keyChanceMap.size() == 0)  
               return null;  
            
          Integer sum = 0;  
          for (Integer value : keyChanceMap.values()) {  
               sum += value;  
          }  
          Integer rand = new Random().nextInt(sum) + 1;  
          for (Map.Entry<String, Integer> entry : keyChanceMap.entrySet()) {  
               rand -= entry.getValue();  
               if(rand <= 0) {  
                    return entry.getKey();  
               }  
          }  
          return null;  
     }  
     
     
	 public static void main(String[] args) {  
         Map<String, Integer> keyChanceMap = new HashMap<String, Integer>();  
         keyChanceMap.put("a", 40);  
         keyChanceMap.put("b", 10);  
         keyChanceMap.put("c", 50);  
         keyChanceMap.put("d", 0);  
         Map<String, Integer> count = new HashMap<String, Integer>();  
         for (int i = 0; i < 100; i++) {  
              String key = chanceSelect(keyChanceMap);  
              if(count.containsKey(key)) {  
                   count.put(key, count.get(key)+1);  
              }else{  
                   count.put(key, 1);  
              }  
         }  
         for (String key : count.keySet()) {  
              System.out.println(key + ":" + count.get(key));  
         }  
    }  
	     
	     
}
